package me.zhengjie.modules.app.android;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.graph.ElementOrder.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.app.ad.service.AduserTabsDetailService;
import me.zhengjie.modules.app.ad.service.AduserXHotelService;
import me.zhengjie.modules.app.ad.service.AduserXMovieService;
import me.zhengjie.modules.app.ad.service.AduserXScreenService;
import me.zhengjie.modules.app.ad.service.dto.AduserTabsDetailDto;
import me.zhengjie.modules.app.ad.service.dto.AduserTabsDetailQueryCriteria;
import me.zhengjie.modules.app.ad.service.dto.AduserXHotelDto;
import me.zhengjie.modules.app.ad.service.dto.AduserXHotelQueryCriteria;
import me.zhengjie.modules.app.ad.service.dto.AduserXMovieDto;
import me.zhengjie.modules.app.ad.service.dto.AduserXMovieQueryCriteria;
import me.zhengjie.modules.app.ad.service.dto.AduserXScreenDto;
import me.zhengjie.modules.app.ad.service.dto.AduserXScreenQueryCriteria;
import me.zhengjie.modules.app.device.service.SettingBindInfoService;
import me.zhengjie.modules.app.device.service.dto.SettingBindInfoQueryCriteria;
import me.zhengjie.modules.app.hotel.domain.HotelInfo;
import me.zhengjie.modules.app.hotel.repository.HotelInfoRepository;
import me.zhengjie.modules.app.hotel.service.HotelInfoService;
import me.zhengjie.modules.app.hotel.service.dto.HotelInfoDto;
import me.zhengjie.modules.app.hotelroom.service.HoteRoomInfoService;
import me.zhengjie.modules.app.tabs.domain.TabsInfo;
import me.zhengjie.modules.app.tabs.repository.TabsInfoRepository;
import me.zhengjie.modules.app.tabs.service.TabsInfoService;
import me.zhengjie.modules.app.tabs.service.dto.TabsInfoDto;
import me.zhengjie.modules.app.tabs.service.dto.TabsInfoQueryCriteria;
import me.zhengjie.modules.app.tabsresource.service.TabsResourceInfoService;
import me.zhengjie.modules.app.tabsresource.service.dto.TabsResourceInfoDto;
import me.zhengjie.modules.app.tabsresource.service.dto.TabsResourceInfoQueryCriteria;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;

@RestController
@RequiredArgsConstructor
@Api(tags = "获取数据结构")
@RequestMapping("/api/update")
public class UpdateController {

    private final HotelInfoRepository hotelInfoRepository;
    private final AduserXHotelService aduserXHotelService;
    private final AduserXMovieService aduserXMovieService;
    private final AduserXScreenService aduserXScreenService;  
    private final TabsInfoService tabsInfoService;
    private final TabsInfoRepository tabsInfoRepository;
    private final TabsResourceInfoService tabsResourceInfoService;
    private final AduserTabsDetailService aduserTabsDetailService;
    
	@Log("获取所有数据结构")
	@ApiOperation("获取所有数据结构")
	@GetMapping(value = "/data")
	public ResponseEntity<Object> download(HttpServletResponse response, String hotelNo) throws IOException {
		JSONObject resultObj = new JSONObject();
		Gson gson = new Gson();
		HotelInfo hotelInfo = hotelInfoRepository.findByHotelNo(hotelNo);
		System.out.println(gson.toJson(hotelInfo));
		JSONObject hotelInfoObj = JSONObject.parseObject(JSONObject.toJSONString(hotelInfo));
		
		//开机视频
		resultObj.put("openMovieInfo", hotelInfoObj);
		//欢迎页
		resultObj.put("hotelWelcomeInfo", hotelInfoObj);
		
		//开机广告
		AduserXHotelQueryCriteria criteria = new AduserXHotelQueryCriteria();
		criteria.setHotelId(hotelInfo.getId());
		
		List<AduserXHotelDto> aduserXHotelDtos = aduserXHotelService.queryAll(criteria);
    	List<AduserXMovieDto> aduserXMovieDtos = null;
    	AduserXMovieQueryCriteria aduserXMovieQueryCriteria = new AduserXMovieQueryCriteria();
    	if(aduserXHotelDtos != null && aduserXHotelDtos.size() > 0) {
        	aduserXMovieQueryCriteria.setAdUserId(aduserXHotelDtos.get(0).getUserId());
        	aduserXMovieDtos = aduserXMovieService.queryAll(aduserXMovieQueryCriteria);
    	}
    	if(aduserXMovieDtos == null || aduserXMovieDtos.size() < 1) {
    		resultObj.put("openAdInfo", new AduserXMovieDto());
    	}else {
    		resultObj.put("openAdInfo", aduserXMovieDtos.get(0));
    	}
    	
		
		//屏保
    	aduserXHotelDtos = aduserXHotelService.queryAll(criteria);
    	List<AduserXScreenDto> aduserXScreenDtos = null;
    	AduserXScreenQueryCriteria aduserXScreenQueryCriteria = new AduserXScreenQueryCriteria();
    	if(aduserXHotelDtos != null && aduserXHotelDtos.size() > 0) {
    		aduserXScreenQueryCriteria.setAdUserId(aduserXHotelDtos.get(0).getUserId());
        	aduserXScreenDtos = aduserXScreenService.queryAll(aduserXScreenQueryCriteria);
    	}
    	if(aduserXScreenDtos == null ) {
    		resultObj.put("screenInfo", new AduserXMovieDto());
        	
    	}
    	resultObj.put("screenInfo", aduserXScreenDtos);
    	
    	//选项卡
    	Pageable pageable = new PageRequest(0,1000,Sort.Direction.DESC,"tabSeq");
    	
    	TabsInfoQueryCriteria tabQueryCriteria = new TabsInfoQueryCriteria();
    	tabQueryCriteria.setHotelId(hotelInfo.getId());
        Page<TabsInfo> page = tabsInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,tabQueryCriteria,criteriaBuilder),pageable);
    	List<TabsInfo> tabs = page.getContent();
    	TabsInfo tabsInfo = null;
    	JsonArray tabsArray = new JsonArray();
    	JsonObject tabsObj = null;
//    	Gson gson = new Gson();
    	JsonObject tempObj = null;
    	for(int index = 0; index < tabs.size(); index ++) {
    		tabsInfo = tabs.get(index);
    		tempObj = new JsonObject();
    		tabsObj = new JsonObject();
    		tempObj.addProperty("id", tabs.get(index).getId());
    		tempObj.addProperty("tabSeq", tabs.get(index).getTabSeq());
    		tempObj.addProperty("tabIcon", tabs.get(index).getTabIcon());
    		tempObj.addProperty("tabIconSelected", tabs.get(index).getTabIconSelected());
    		tempObj.addProperty("hotelId", tabs.get(index).getHotelId());
    		tempObj.addProperty("hotelName", tabs.get(index).getHotelName());
    		tempObj.addProperty("tabName", tabs.get(index).getTabName());
    		
    		tabsObj.add("info", tempObj);
    		tabsObj.add("resources", tabsResource(hotelInfo.getId(), tabs.get(index).getId()));
    		tabsArray.add(tabsObj);
    	}
    	resultObj.put("tabs", JSONArray.parseArray(tabsArray.toString()));
    	return new ResponseEntity<>(resultObj,HttpStatus.OK);
	}
	
	public JsonArray tabsResource(String hotelId, String tabsId) {
		Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {

			@Override
			public JsonElement serialize(LocalDateTime src, java.lang.reflect.Type typeOfSrc,
					JsonSerializationContext context) {
				// TODO Auto-generated method stub
				return new JsonPrimitive(src.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
			}
		
		}).create();
		
		TabsResourceInfoQueryCriteria criteria = new TabsResourceInfoQueryCriteria();
		criteria.setHotelId(hotelId);
		criteria.setTabsId(tabsId);
		List<TabsResourceInfoDto> tabsResourceInfoDtos = tabsResourceInfoService.queryAll(criteria);
    	
    	//查询tabsinfo 相关信息
    	TabsInfoDto tabsInfoDto = tabsInfoService.findById(tabsId);
    	
    	//查询酒店是否分配广告商，如果没有分配直接返回查询出来的数据，如果分配了，需要将广告商的广告数据进行组装
    	AduserXHotelQueryCriteria aduserXHotelQueryCriteria = new AduserXHotelQueryCriteria();
    	aduserXHotelQueryCriteria.setHotelId(hotelId);
    	List<AduserXHotelDto> aduserXHotelDtos = aduserXHotelService.queryAll(aduserXHotelQueryCriteria);
    	if(aduserXHotelDtos != null && aduserXHotelDtos.size() > 0) {
    		//拼接数据,查询广告商配置的坑位广告信息
    		AduserTabsDetailQueryCriteria aduserTabsDetailQueryCriteria = new AduserTabsDetailQueryCriteria();
    		aduserTabsDetailQueryCriteria.setAdUserId(aduserXHotelDtos.get(0).getUserId());
    		aduserTabsDetailQueryCriteria.setTabIndex(tabsInfoDto.getTabSeq());
    		
    		List<AduserTabsDetailDto> aduserTabsDetailDtos = aduserTabsDetailService.queryAll(aduserTabsDetailQueryCriteria);
    		//如果查询出来有匹配数据，就替换酒店自己设定的数据，而且只会有一条
    		
    		if(aduserTabsDetailDtos != null && aduserTabsDetailDtos.size() == 1) {
    			List<TabsResourceInfoDto> tabsResourceInfoDtosNew = new ArrayList<TabsResourceInfoDto>();
    			AduserTabsDetailDto aduserTabsDetailDto = aduserTabsDetailDtos.get(0);  
				TabsResourceInfoDto tabsResourceInfoDto = tabsResourceInfoDtos.get(0);
				TabsResourceInfoDto temp = new TabsResourceInfoDto();
//    			if(aduserTabsDetailDto.getApkParams() != null) {
//    				BeanUtils.copyProperties(tabsResourceInfoDto, temp);
//    				temp.setResourceType("apk");
//    				temp.setResourceUrl(aduserTabsDetailDto.getApkParams());
//    				tabsResourceInfoDtosNew.add(temp);
//    			}
				if(aduserTabsDetailDto.getLeftMv() != null) {//视频
					TabsResourceInfoDto temp2 = new TabsResourceInfoDto();
					BeanUtils.copyProperties(tabsResourceInfoDto, temp2);
					temp2.setResourceType("mv");
					temp2.setResourceUrl(aduserTabsDetailDto.getLeftMv());
					temp2.setResourceDisplayPosition("left");
    				tabsResourceInfoDtosNew.add(temp2);
    			}
				if(aduserTabsDetailDto.getRightPics() != null) {
    				String arrayStr = aduserTabsDetailDto.getRightPics();
    				JSONArray jsonArray = JSONArray.parseArray(arrayStr);
					TabsResourceInfoDto temp3 = new TabsResourceInfoDto();
    				for(int index = 0; index < jsonArray.size(); index ++) {
    					temp3 = new TabsResourceInfoDto();
						BeanUtils.copyProperties(tabsResourceInfoDto, temp3);
						temp3.setResourceType("img");
						temp3.setResourceUrl(jsonArray.getJSONObject(index).getString("url"));
						temp3.setResourceDisplayPosition("right");
        				tabsResourceInfoDtosNew.add(temp3);
    				}
    			}
				
				for(int index = 0; index < tabsResourceInfoDtos.size(); index ++) {
					if("apk".equals(tabsResourceInfoDtos.get(index).getResourceType())) {
						tabsResourceInfoDtosNew.add(tabsResourceInfoDtos.get(index));
					} else if("img".equals(tabsResourceInfoDtos.get(index).getResourceType()) && "click".equals(tabsResourceInfoDtos.get(index).getResourceDisplayPosition())) {
						tabsResourceInfoDtosNew.add(tabsResourceInfoDtos.get(index));
					}
				}

				tabsResourceInfoDtos.clear();
				tabsResourceInfoDtos.addAll(tabsResourceInfoDtosNew);
    		}
    	}
//    	JSONArray resultArray = JSONArray.parseArray(JSON.toJSONString(tabsResourceInfoDtos));
    	JsonArray resultArray = new JsonParser().parse(gson.toJson(tabsResourceInfoDtos)).getAsJsonArray();
    	return resultArray;
	}
}
